package org.mcflier.appuntamento.tasks;

import java.util.logging.Logger;

import org.mcflier.appuntamento.core.Factory;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.core.logger.LoggerManager;

public abstract class AbstractTask extends Thread {
	
	private long delay;
	protected Logger logger;
	protected boolean isStopped;
	
	public AbstractTask(String name, long delay) throws ModulesException{
		if(name==null)
			throw new NullPointerException("Task name must not be null");
		
		if(delay<0)
			throw new IllegalArgumentException("Delay must be equal or greater than zero");
		
		this.setName(name);
		this.delay = delay;
		this.logger = ((LoggerManager)Factory.getInstance().getModuleInstance(Factory.MODULE_LOGGER)).getLogger(this.getClass().getName());
		this.isStopped = true;
	}

	public long getDelay() {
		return delay;
	}
	
	public boolean isStopped(){
		return this.isStopped;
	}
	
	@Override
	public void run(){
		this.isStopped = false;
		while(!this.isStopped){
			try {
				this.doSomething();
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				this.logger.warning("Error delaying the task '"+this.getName()+"'");
			}
		}
	}
	
	public void stopTask(){
		this.isStopped=true;
	}

	public abstract void doSomething();
}
